<template>
  <div class="login-container">
    <div class="login-form-content">
      <svg-icon class="login-icon" icon-class="login"></svg-icon>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" :class="['login-form', step == 2 && 'checked']">
        <div class="app-label">{{title}}</div>
        <template v-if="step == 1">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="请输入登录手机号">
              <span slot="prefix" class="input-label">账号</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码"
              @keyup.enter.native="handleLogin">
              <span slot="prefix" class="input-label">密码</span>
            </el-input>
          </el-form-item>
          <div class="other-content">
            <span class="other-btn">
              <i class="btn-txt" @click="jumpPage('forgetPwd')">忘记密码</i>
            </span>
            <span class="other-btn" v-if="!(['admin', 'agent', 'shop'].includes(register))">
              <i class="other-txt">没有账户，</i>
              <i class="btn-txt" @click="jumpPage('appRegister')">立即注册</i>
            </span>
          </div>
          <div class="login-btn-content">
            <el-button :loading="loading" size="medium" type="primary" style="width:100%;"
              @click.native.prevent="handleLogin">
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
          </div>
          <div class="checkbox-content flex-normal">
            <el-checkbox v-model="loginForm.rememberMe"></el-checkbox>
            <div class="checkbox-desc flex-normal">
              <span class="desc-txt">我已阅读并同意</span>
              <span class="desc-btn m">车多多用户服务协议</span>
              <span class="desc-txt m">及</span>
              <span class="desc-btn m">隐私权政策</span>
            </div>
          </div>
        </template>
        <template v-if="step == 2">
          <div class="back-step flex-normal">
            <span class="el-icon-back" @click="step = 1"></span>
            <span class="step-txt" @click="step = 1">账户验证</span>
          </div>
          <div class="tel-content">
            已向您尾号{{dealTel()}}的手机发送短信验证
          </div>
          <el-form-item prop="username">
            <el-input v-model="codeParams.code" type="text" auto-complete="off" placeholder="验证码">
              <span slot="prefix" class="input-label">验证码</span>
              <el-button type="text" :loading="timerObj.loading" slot="suffix" 
              class="tel-code-btn" @click="getCode">{{timerObj.tips}}</el-button>
            </el-input>
          </el-form-item>
          <div class="login-btn-content">
            <el-button :loading="codeLoading" size="medium" type="primary" style="width:100%;"
              @click.native.prevent="handleCodeLogin">
              <span v-if="!loading">提交验证</span>
              <span v-else>验证中...</span>
            </el-button>
          </div>
        </template>
      </el-form>
    </div>
  </div>
</template>

<script>
import {mapActions} from 'vuex'
import { getCode } from '@/api/common/index'
import { isPhoneNum } from '@/utils/tools.js'
export default {
  name: "Login",
  data() {    
    const validatePhoneNum =(rule, value, callback) => {
      if (!isPhoneNum(`${value}`)) {
        callback(new Error('请输入正确手机号'));
      } else {
        callback();
      }
    }
    return {
      step: 1,
      timerObj: {
        timer: null,
        seconds: 60,
        loading: false,
        tips: '获取验证码'
      },
      codeParams: {}, //二次校验参数
      title: process.env.VUE_APP_TITLE,
      loginForm: {
        username: "",
        password: "",
        code: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
          { validator: validatePhoneNum, trigger: 'blur'}
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      codeLoading: false,
      // 注册开关
      register: process.env['VUE_APP_RULE'],
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  mounted(){
    let _self = this
    if(_self.timerObj.timer){
      clearInterval(_self.timerObj.timer)
      _self.timerObj.timer = null
    }
  },
  methods: {
    ...mapActions(['Login']),
    dealTel(){
      let tel = this.codeParams.username
      if(!tel || tel == '') return ''
      return tel.replace(/d{7}(d{4})/,'*******$1')
    },
    startTimer(){
      let _self = this
      _self.timerObj.timer = setInterval(() => {
        _self.timerObj.seconds--
        if(_self.timerObj.seconds === 0){
          _self.timerObj.seconds = 60
          _self.timerObj.loading = false
          _self.timerObj.tips = '重新获取验证码'
          clearInterval(_self.timerObj.timer)
        }else{
          _self.timerObj.tips = `${_self.timerObj.seconds}s 后重新获取`
        }
      }, 1000)
    },
    async getCode(){
      let _self = this, {username} = this.codeParams
      if(!isPhoneNum(username)) return _self.$message.error('手机号格式错误')
      _self.startTimer()
      _self.timerObj.loading = true
      await getCode(username).then(res => {
        _self.$message.success('验证码已发送');
      }).catch((err) => {
        _self.timerObj.loading = false
        _self.timerObj.seconds = 60
        clearInterval(_self.timerObj.timer)
      })
    },
    jumpPage(name){
      this.$router.push({name})
    },
    handleLogin() {
      let _self = this
      _self.$refs.loginForm.validate(valid => {
        if (valid) {
          _self.loading = true;
          _self.Login({key: 'pwd', userInfo: _self.loginForm}).then((res) => {
            if(res.action == 'login'){
              _self.$router.push({ path: "/" }).catch(() => { });
            }else{
              this.codeParams.username = res.username
              _self.step = 2
            }
          }).finally(() => {
            _self.loading = false;
          });
        }
      });
    },
    handleCodeLogin() {
      let _self = this, {code} = this.codeParams
      if(!code || code == '') return _self.$message.error('验证码不能为空')
      _self.codeLoading = true;
      _self.Login({key: 'code', userInfo: _self.codeParams}).then((res) => {
        if(res.action == 'login'){
          _self.$router.push({ path: "/" }).catch(() => { });
        }else{
          _self.step = 2
        }
      }).finally(() => {
        _self.codeLoading = false;
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login-container {
  display: flex;
  height: 100vh;
  flex-direction: column;
  background-color: #fff;
  padding: vh(120) vw(200) vh(100) vw(200);
}

.login-form-content {
  position: relative;
  flex: 1;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30px;  
  align-items: center;
  border-radius: vh(80);
  box-shadow: vh(20) vh(-20) 0 vh(10) rgba(174, 173, 173, 0.09);
  padding: 0 30px;
  .app-label{
    font-size: vh(24);
    color: #3D3D3D;
    margin-bottom: vh(60);
  }
  .login-icon{
    display: block;
    width: 100%;
    height: vh(486);
  }
  .login-form ::v-deep{
    min-height: vh(400);
    top: vh(147);
    right: vw(216);
    border: 1px solid #DDDDDD;
    border-radius: vh(5);
    box-shadow: 0 vh(5) vh(10) 0 rgba(0, 0, 0, 0.3);
    padding: vh(36) vw(33);
    overflow: hidden;
    .input-label{
      font-size: 13px;
      color: #097BDF;
      padding-right: vh(10);
    }
    .el-input__inner{
      padding-left: 60px;
    }
    .el-form-item{
      margin-bottom: vh(20);
    }
  }
  .other-content{
    display: flex;
    align-items: center;
    justify-content: end;
    .other-btn{
      margin-left: vw(24);
      margin-top: vh(-8);
      .btn-txt, .other-txt{
        font-size: vh(12);
        color: #3D3D3D;
        font-style: normal;
      }
      .btn-txt{
        cursor: pointer;
        color: #097BDF;
      }
    }
  }
  .checked ::v-deep{
    .app-label{
      margin-bottom: vh(40);
    }
    .back-step{
      font-size: vh(16);
      color: #3D3D3D;
      .el-icon-back{
        cursor: pointer;
      }
      .step-txt{
        margin-left: vw(15);
        cursor: pointer;
      }
    }
    .tel-content{
      font-size: vh(12);
      color: #3D3D3D;
      margin-top: vh(35);
      margin-bottom: vh(15);
    }
    .el-input__inner{
      padding-left: 60px !important;
    }
    .tel-code-btn{
      font-size: vh(12);
      color: #097BDF;
      cursor: pointer;
    }
    .login-btn-content{
      margin-top: vh(90);
    }
  }
}

.login-btn-content ::v-deep{
  margin-top: vh(40);
  .el-button {
    height: vh(50);
    padding: 0;
  }

  .el-button--primary {
    background: #097BDF;
    border-color: #097BDF;
    font-size: vh(16);
  }
}
.checkbox-content ::v-deep{
  margin-top: vh(18);
  .el-checkbox__input{
    margin-bottom: vh(-1);
  }
  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #097BDF;
    border-color: #097BDF;
  }
  .checkbox-desc{
    margin-left: vh(8);
    .desc-txt, .desc-btn{
      font-size: vh(12);
      color: #3D3D3D;
    }
    .desc-btn{
      color: #097BDF;
      cursor: pointer;
    }
    .m{
      margin-left: vh(3);
    }
  }
}
</style>
